import React from "react";
import GoBack from "@/components/TheGoBack";
import TheImage from "@/components/TheImage";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import "../../style/style.less";
import {
  apiGetGoodsInfoDetail,
  apiGetGoodsSkuPutway,
} from "@/request/mallManagement";
import _ from "lodash";
import { Space, Table, Tag } from "antd";

class Detail extends React.Component {
  state = {
    basicData: [],
    columns: [],
    dataSource: [],
    productTxt: "",
    specificationsDetailed: [],
    specificationsColumns: [
      {
        title: "参数项",
        dataIndex: "specificationsName",
      },
      {
        title: "值",
        dataIndex: "specificationsValue",
      },
    ],
    rowHide: false,
    goodsTagOptions: [],
  };
  async componentDidMount() {
    let res = await React.$post('/management/tSysDictionaries/list', { type: "goods_tag" })
    let goodsTagOptions = []
    res.data.map((v) => {
      goodsTagOptions.push({ label: v.name, value: v.dictionariesId })
    })
    this.setState({
      goodsTagOptions
    })
    await this.getData();

  }
  onShelf = (skuId, skuStatus) => {
    React.$confirm({
      title: "您确定上架该商品吗？",
      onOk: async () => {
        await apiGetGoodsSkuPutway({ skuId, skuStatus });
        await this.getData();
      },
    });
  };
  offShelf = (skuId, skuStatus) => {
    React.$confirm({
      title: "您确定下架该商品吗？",
      onOk: async () => {
        await apiGetGoodsSkuPutway({ skuId, skuStatus });
        await this.getData();
      },
    });
  };
  //同步金蝶库存
  synchronized = async (skuid, materialid) => {
    // console.log(skuid,materialid)
    let params = {
      skuId: skuid,
      // materialId : materialid
    };
    let res = await React.$post("/management/goodsInfo/syncStock", params);
    if (res.code === 0) {
      this.getData();
    }
  };
  getData = async () => {
    const { productId } = this.props.match.params;
    const { goodsTagOptions } = this.state
    if (this.props.location.search == "?rowhide") {
      this.setState({
        rowHide: true,
      });
    }
    let res = await apiGetGoodsInfoDetail({ goodsId: productId });
    console.log(goodsTagOptions)
    if (res.code === 0 && res.data) {
      const { goodsInfo, skuInfo, specificationsDetailed } = res.data;
      let defaultTag = []
      let goodsTag = goodsInfo.goodsTag !== null ? goodsInfo.goodsTag.split(',') : []
      goodsTagOptions.map((v) => {
        goodsTag.map((g) => {
          if (v.value === g) {
            defaultTag.push(v)
          }
        })
      })
      console.log(defaultTag);
      let basicData = [
        {
          value: goodsInfo.goodsClassifyName,
          text: "商品分类",
        },
        {
          value: (
            defaultTag.map((v) => {
              return <Tag>{v.label}</Tag>
            })
          ),
          text: "商品标签",
        },
        {
          value: goodsInfo.brandName,
          text: "商品品牌",
        },
        {
          value: goodsInfo.goodsName,
          text: "商品名称",
        },
        // {
        //   value: (
        //     <React.$Price
        //       price={goodsInfo.originalPrice || ""}
        //       color="#7F7F7F"
        //     />
        //   ),
        //   text: "商品原价",
        // },
        // {
        //   value: (
        //     <React.$Price
        //       price={goodsInfo.currentPrice || ""}
        //       color="#7F7F7F"
        //     />
        //   ),
        //   text: "商品现价",
        // },
        {
          value: (
            <Space>
              {goodsInfo.goodsShowImages.split(",").map((v) => {
                return <TheImage width={80} height={80} src={v} />;
              })}
            </Space>
          ),
          text: "商品图片",
        },
        {
          value: goodsInfo.otherDelivery?'是':'否',
          text: "代发货商品",
        },
      ];
      let dataSource = skuInfo.map((v, i) => {
        let obj = {};
        v.skuAttribute.forEach((j, k) => {
          obj[k] = j.value;
        });
        obj.materialId = v.materialId;
        obj.materialName = v.materialName;
        obj.skuOriginalPrice = <React.$Price price={v.skuOriginalPrice} />;
        obj.skuCurrentPrice = <React.$Price price={v.skuCurrentPrice} />;
        obj.stock = parseInt(v.stock).toLocaleString();
        obj.skuIntegral = parseInt(v.skuIntegral).toLocaleString();
        obj.skuWeight = `${v.skuWeight / 1000}kg`;
        // obj.skuWeight = `${React.$transNum(v.skuWeight, -1, -3)}kg`
        obj.skuDescription = v.skuDescription;
        obj.imageFile = <TheImage src={v.imageFile} width={80} height={80} />;
        obj.SKUId = v.SKUId;
        obj.materialId = v.materialId;
        obj.skuId = v.skuId;
        obj.skuStatus = v.skuStatus;
        return obj;
      });
      let columns = [];
      _.forEach(skuInfo[0].skuAttribute, (v, i) => {
        columns.push({
          title: v.key,
          dataIndex: i,
          key: i,
        });
      });
      columns = columns.concat([
        {
          title: "物料ID",
          dataIndex: "materialId",
          key: "materialId",
        },
        {
          title: "商品物料名称(仓库用 APP不显示)",
          dataIndex: "materialName",
          key: "materialName",
        },
        {
          title: "原价",
          dataIndex: "skuOriginalPrice",
          key: "skuOriginalPrice",
        },
        {
          title: "现价",
          dataIndex: "skuCurrentPrice",
          key: "skuCurrentPrice",
        },
        {
          title: "库存",
          dataIndex: "stock",
          key: "stock",
        },
        {
          title: "重量(KG)",
          dataIndex: "skuWeight",
          key: "skuWeight",
        },
        {
          title: "描述",
          dataIndex: "skuDescription",
          key: "skuDescription",
        },
        {
          title: "图片",
          dataIndex: "imageFile",
          key: "imageFile",
        },
        // {
        //   title: '同步金蝶库存',
        //   render: (text, record) => {
        //     return (
        //       <TheButton onClick={() => {
        //         this.synchronized( record.SKUId,record.materialId)
        //       }} >同步库存</TheButton>

        //     )
        //   }
        // },
      ]);
      console.log(this.state.rowHide);
      if (this.state.rowHide) {
        columns.push({
          title: "操作",
          render: (text, record) => {
            console.log(record);
            return (
              <div>
                {record.skuStatus === "N" && (
                  <TheButton
                    hasPermi={["mall:sku:OnShelf"]}
                    onClick={() => this.onShelf(record.SKUId, "Y")}
                  >
                    上架
                  </TheButton>
                )}
                {record.skuStatus === "Y" && (
                  <TheButton
                    hasPermi={["mall:sku:OnShelf"]}
                    onClick={() => this.offShelf(record.SKUId, "N")}
                  >
                    下架
                  </TheButton>
                )}
              </div>
            );
          },
        });
      }
      this.setState(
        {
          columns: columns,
          dataSource,
          basicData,
          productTxt: goodsInfo.productTxt,
          specificationsDetailed,
          freightTemplateName: goodsInfo.freightTemplateName,
        },
        () => {
          console.log(this.state.columns);
        }
      );
    }
  };
  render() {
    const {
      basicData,
      columns,
      dataSource,
      productTxt,
      specificationsDetailed,
      specificationsColumns,
      freightTemplateName,
    } = this.state;
    return (
      <div className="commodity-list-detail p-layout-box">
        <GoBack history={this.props.history} title={"商品详情"} />
        <div className="detail-content">
          <div className="commodity-card">
            <div className="title">基本信息</div>
            <div className="content basic">
              {basicData.map((v, i) => {
                return (
                  <div>
                    <p>{v.text}:</p>
                    <div>{v.value}</div>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="commodity-card">
            <div className="title">交易信息</div>
            <div className="content basic">
              <div>
                <p>运费模板:</p>
                <div>{freightTemplateName}</div>
              </div>
            </div>
          </div>
          <div className="commodity-card">
            <div className="title">参数信息</div>
            <div className="content">
              <TheTable
                columns={specificationsColumns}
                dataSource={specificationsDetailed}
              />
            </div>
          </div>
          <div className="commodity-card">
            <div className="title">商品规格信息</div>
            <div className="content">
              <Table
                columns={columns}
                dataSource={dataSource}
                pagination={false}
              />
              {/* <TheTable
                columns={columns}
                dataSource={dataSource}
              /> */}
            </div>
          </div>
          <div className="commodity-card">
            <div className="title">商品详情</div>
            <div className="content">
              <div
                style={{ overflowX: "auto" }}
                dangerouslySetInnerHTML={{ __html: productTxt }}
              />
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default Detail;
